package com.situ.meetingRoom.listener;

import com.situ.meetingRoom.entity.User;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.HashSet;
import java.util.Set;

@WebListener
//监听器
public class SessionListener implements
        //Request
        //ServletRequestListener,//生命周期
        //ServletRequestAttributeListener,//属性变化
        //session
        HttpSessionListener,//生命周期
        HttpSessionAttributeListener//属性变化
        //Application对象
        //ServletContextListener,//生命周期
        //ServletContextAttributeListener //属性变化
{
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        //当一个Session对象被创建时,该方法会被调用
        System.out.println("Session创建");
        //记录当前访问网站的用户
        ServletContext application = se.getSession().getServletContext();
        Integer onlineCount = (Integer) application.getAttribute("onlineCount");
        if (onlineCount == null) {
            onlineCount = 0;
        }
        onlineCount++;
//        写回去
        application.setAttribute("onlineCount", onlineCount);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        //当一个Session对象被销毁时,该方法会被调用
        System.out.println("Session创建");
        //记录当前访问网站的用户
        ServletContext application = se.getSession().getServletContext();
        Integer onlineCount = (Integer) application.getAttribute("onlineCount");
        if (onlineCount == null) {
            onlineCount = 0;
        }
        onlineCount--;
//        写回去
        application.setAttribute("onlineCount", onlineCount);
    }

    //属性监听

    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        System.out.println("Session添加了属性");
        if ("user".equals(event.getName())){
            User user = (User) event.getValue();
            //Application对象
            ServletContext application = event.getSession().getServletContext();
            Set<User> loginUsers = (Set<User>) application.getAttribute("loginUsers");
            if (loginUsers == null){
                loginUsers = new HashSet<>();
            }
            loginUsers.add(user);
            application.setAttribute("loginUsers",loginUsers);
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        System.out.println("Session删除了属性");
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        System.out.println("Session替换了属性");
    }
}
